//
//  DCFCommonUtils.m
//  DCF
//
//  Created by 吴文拼 on 2017/12/26.
//  Copyright © 2017年 吴文拼. All rights reserved.
//

#import "DCFCommonUtils.h"
#import "ServerAPISetting.h"

@implementation DCFCommonUtils

#pragma mark --Common通用
+ (void)delay:(NSTimeInterval)time cmp:(void (^)(void))cmp {
    dispatch_time_t dTime = dispatch_time(DISPATCH_TIME_NOW, time * NSEC_PER_SEC);
    dispatch_after(dTime, dispatch_get_main_queue(), cmp);
}

#pragma mark --NSString字符串相关
+ (BOOL)isEmpty:(id)obj {
    if ([obj isKindOfClass:[NSString class]]) {
        NSString *str = (NSString *)obj;
        if (!str || str.length == 0 || [str containsString:@"(null)"] || str == NULL) {
            return YES;
        } else {
            return NO;
        }
    }
    if ([obj isKindOfClass:[NSArray class]]) {
        NSArray *arr = (NSArray *)obj;
        if (!arr || arr.count == 0) {
            return YES;
        } else {
            return NO;
        }
    }
    if ([obj isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dic = (NSDictionary *)obj;
        if (!dic || dic.count == 0) {
            return YES;
        } else {
            return NO;
        }
    }
    if ([obj isKindOfClass:[NSSet class]]) {
        NSSet *set = (NSSet *)obj;
        if (!set || set.count == 0) {
            return YES;
        } else {
            return NO;
        }
    }
    return YES;
}

+ (NSString *)trim:(NSString *)string {
    if (string == nil) {
        return nil;
    }
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    return [string stringByReplacingOccurrencesOfString:@"\u2006" withString:@""];
}

+ (CGSize)string:(NSString *)string size:(CGSize)size fontSize:(CGFloat)fontSize {
    if ([self isEmpty:string]) {
        return CGSizeZero;
    }
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    attributes[NSFontAttributeName] = [UIFont systemFontOfSize:fontSize];
    CGSize boundSize = [string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil].size;
    boundSize.width = ceil(boundSize.width);//计算出来的是小数，显示时应该向上取整数，官方文档说的。
    boundSize.height = ceil(boundSize.height);
    return boundSize;
}

+ (NSArray *)stringRegularMatch:(NSString *)origin pattern:(NSString *)pattern {
    if ([self isEmpty:origin] || [self isEmpty:pattern]) {
        return nil;
    }
    NSError *error = nil;
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    if (error) {
        return nil;
    }
    NSArray *matches = [regular matchesInString:origin options:NSMatchingReportCompletion range:NSMakeRange(0, origin.length)];
    if ([self isEmpty:matches]) {
        return nil;
    }
    NSMutableArray *rangeArray = [NSMutableArray array];
    for (NSTextCheckingResult *match in matches) {
        [rangeArray addObject:[NSValue valueWithRange:match.range]];
    }
    return rangeArray;
}

+(NSString *)convertToJsonData:(NSDictionary *)dict{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}

+ (void)openUrlWithUrlStr:(NSString *)urlStr completeBlock:(void (^)(BOOL))complete{
    NSURL *useUrl = [NSURL URLWithString:urlStr];
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=10.0) {
        [[UIApplication sharedApplication] openURL:useUrl options:@{} completionHandler:^(BOOL success) {
            if (complete) {
                complete(success);
            }
        }];
    }else{
        [[UIApplication sharedApplication] openURL:useUrl];
    }
}

+(void)openSystemSettingWithcompleteBlock:(void (^)(BOOL))complete{
    [self openUrlWithUrlStr:UIApplicationOpenSettingsURLString completeBlock:complete];
}

+ (void)goToAppStore{
    NSString *itunesurl = nil;
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=11.0) {
        itunesurl = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/cn/app/id%@?mt=8&action=write-review",APP_STORE_ID];
    }else {
        itunesurl = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%@",APP_STORE_ID];
    }
    [self openUrlWithUrlStr:itunesurl completeBlock:^(BOOL success) {
        
    }];
}

//时间戳之间的天数
+ (NSInteger)getDaysFromTs:(NSInteger)tsStart withTsEnd:(NSInteger)tsEnd
{
    NSString *startDateStr = [DCFCommonUtils stringFromTimeSP:tsStart formatter:typeYearMonthDay];
    NSString *endDateStr = [DCFCommonUtils stringFromTimeSP:tsEnd formatter:typeYearMonthDay];
    NSDate *startDate = [DCFCommonUtils dateFromString:startDateStr withFormat:@"yyyy-MM-dd"];
    NSDate *endDate = [DCFCommonUtils dateFromString:endDateStr withFormat:@"yyyy-MM-dd"];
    return [DCFCommonUtils caculateDays:startDate To:endDate];
}

//时间转化为时间戳
+ (NSString *)getTimeStampFromString:(NSString *)dateStr withFormat:(NSString *)formatStr
{
    NSDate *date = [DCFCommonUtils dateFromString:dateStr withFormat:formatStr];
    return [NSString stringWithFormat:@"%lld",[NSDate milliSecondsFromDate:date]];
}

#pragma timestamp
+ (NSString *)getTimestampFromDate:(NSDate *)date//10位到秒 不用这个
{
    return [NSString stringWithFormat:@"%ld", (long)([date timeIntervalSince1970])];
}

//根据string返回date
+ (NSDate *)dateFromString:(NSString *)string withFormat:(NSString *)format
{
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    if (format)
    {
        [inputFormatter setDateFormat:format];
    }
    NSDate *date = [inputFormatter dateFromString:string];
    return date;
}

//时间戳转化为时间
+(NSString *)stringFromTimeSP:(long long)_timesp //时间戳转化
{
    NSDate *detailDate = [NSDate dateFromMilliSeconds:_timesp];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *currentDateStr = [dateFormatter stringFromDate: detailDate];
    return currentDateStr;
}

+ (NSString *)stringFromTimeSP:(long long)_timesp formatter:(FormatterType)formatterType
{
    NSDate *detailDate = [NSDate dateFromMilliSeconds:_timesp];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    switch (formatterType) {
        case typeOnlyYear:
        {
            [dateFormatter setDateFormat:@"yyyy"];
        }
            break;
        case typeOnlyMoth:
        {
            [dateFormatter setDateFormat:@"MM"];
        }
            break;
        case typeOnlyDay:
        {
            [dateFormatter setDateFormat:@"dd"];
        }
            break;
        case typeOnlyHour:
        {
            [dateFormatter setDateFormat:@"HH"];
        }
            break;
        case typeOnlyMin:
        {
            [dateFormatter setDateFormat:@"mm"];
        }
            break;
        case typeYearMonthDay:
        {
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        }
            break;
        case typeYearMonthDayHourMin:
        {
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        }
            break;
        case typeYearMonthDayHourMinSec:
        {
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        }
            break;
        case typeMonthAndDay:
        {
            [dateFormatter setDateFormat:@"MM-dd"];
        }
            break;
        case typeMonthDayHourMin:
        {
            [dateFormatter setDateFormat:@"MM-dd HH:mm"];
        }
            break;
        case typeHourAndMin:
        {
            [dateFormatter setDateFormat:@"HH:mm"];
        }
            break;
            
        default:
            break;
    }
    NSString *currentDateStr = [dateFormatter stringFromDate: detailDate];
    return currentDateStr;
}

//计算两个日期之间的天数
+ (NSInteger)caculateDays:(NSDate *)startDate To:(NSDate *)endDate
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents * comp = [calendar components:NSCalendarUnitDay fromDate:startDate toDate:endDate options:NSCalendarWrapComponents];
    return comp.day;
}

#pragma mark 获取当前日期  格式如下 yyyyMMddHHmmss
+ (NSString *)getCurrentDate:(FormatterType)formatterType
{
    return [DCFCommonUtils getCurrentDate:formatterType addTimeInterval:0];
}

+ (NSString *)getCurrentDate:(FormatterType)formatterType addTimeInterval:(NSTimeInterval)timeInterval
{
    NSDate *currentDate = [[NSDate alloc]initWithTimeInterval:timeInterval sinceDate:[NSDate date]];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    switch (formatterType) {
        case typeOnlyYear:
        {
            [dateFormatter setDateFormat:@"yyyy"];
        }
            break;
        case typeOnlyMoth:
        {
            [dateFormatter setDateFormat:@"MM"];
        }
            break;
        case typeOnlyDay:
        {
            [dateFormatter setDateFormat:@"dd"];
        }
            break;
        case typeOnlyHour:
        {
            [dateFormatter setDateFormat:@"HH"];
        }
            break;
        case typeOnlyMin:
        {
            [dateFormatter setDateFormat:@"mm"];
        }
            break;
        case typeYearMonthDay:
        {
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        }
            break;
        case typeYearMonthDayHourMin:
        {
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        }
            break;
        case typeMonthAndDay:
        {
            [dateFormatter setDateFormat:@"MM-dd"];
        }
            break;
        case typeMonthDayHourMin:
        {
            [dateFormatter setDateFormat:@"MM-dd HH:mm"];
        }
            break;
        case typeHourAndMin:
        {
            [dateFormatter setDateFormat:@"HH:mm"];
        }
            break;
            
        default:
            break;
    }
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    
    return dateString;
}

+ (float)heightWithFont:(UIFont *)font maxWidth:(float)maxWidth string:(NSString *)string
{
    NSDictionary *attrs = @{NSFontAttributeName:font};
    
    return [string boundingRectWithSize:CGSizeMake(maxWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size.height;
}

+ (float)widthWithFont:(UIFont *)font maxHeight:(float)maxHeight string:(NSString *)string
{
    NSDictionary *attrs = @{NSFontAttributeName:font};
    
    return [string boundingRectWithSize:CGSizeMake(MAXFLOAT, maxHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size.width;
}

+ (NSString *)verifyUrl:(NSString *)url
{
    if (![url hasPrefix:@"http"]&&![url hasPrefix:@"https"])
    {
        url = [NSString stringWithFormat:@"%@%@",DCF_SERVER_HOST_NAME,url];
    }
    return url;
}

//获取range
+ (NSArray *)rangeOfSubString:(NSString *)subStr inString:(NSString *)string
{
    NSMutableArray *rangeArray = [NSMutableArray array];
    
    NSString *string1 = [string stringByAppendingString:subStr];
    NSString *temp;
    for (int i = 0; i < string.length; i++)
    {
        temp = [string1 substringWithRange:NSMakeRange(i, subStr.length)];
        if ([temp isEqualToString:subStr])
        {
            NSRange range = {i,subStr.length};
            [rangeArray addObject: [NSValue valueWithRange:range]];
        }
    }
    return rangeArray;
}

@end
